var gulp = require('gulp'),
    htmlmin = require('gulp-htmlmin'),
    uglify = require('gulp-uglify'),
    pump = require('pump'),
    concat = require('gulp-concat'),
    sourcemaps = require('gulp-sourcemaps'),
    replace = require('gulp-replace'),
    inject = require('gulp-inject'),
    ejs = require('gulp-ejs'),
    gutil = require('gulp-util'),
    copy = require('gulp-copy'),
    useref = require('gulp-useref'),
    gulpif = require('gulp-if'),
    minifyCss = require('gulp-clean-css'),
    rev = require('gulp-rev'),
    imagemin = require('gulp-imagemin'),
    watch = require('gulp-watch'),
    lazypipe = require('lazypipe'),
    fs = require('fs'),
    gulpSequence = require('gulp-sequence'),
    path = require('path'),
    del = require('del'),
    revCollector = require('gulp-rev-collector');
var minifyHTML = require('gulp-minify-html');
var htmlDir = './src.test/html/';
var buildDir = './build/';
/**
 *  拷贝字体
 */
function copyFont(){
    gulp
        .src(['src.test/libs/icomoon/**/*.eot','src.test/libs/icomoon/**/*.svg','src.test/libs/icomoon/**/*.ttf','src.test/libs/icomoon/**/*.woff'])
        .pipe(copy('build/css', {prefix:3}))
}

/**
 * 文件拷贝
 */
gulp.task('copy-font', function () {
    /***
     * 文件监控
     */
    return copyFont();
    //.dest('build');
});
gulp.task('default', function () {
    /***
     * 文件监控
     */
    watch([htmlDir + '**',], {ignoreInitial: true}, function (event) {
        var path_ = event.path.replace(/\\/g, '/');
        console.log('变动文件-->' + path_);
        if (path_) {
            singleFileTask(path_);
        }
    });
    return readOneLevelFile(htmlDir);
});
gulp.task('dev:step1', function () {
    return readOneLevelFile(htmlDir);
});

/**
 * @date 2017-05-08
 * @desc  handle single file by gulp task
 */
function singleFileTask(path_, isPro) {
    if (path_) {
        //零宽正向先行断言
        var path__ = path_.replace('src.test', 'build').replace('html/', '').match(/.*(?=\/.*\.html)/)[0];
        console.log('处理结果输出路径->' + path__);
        if (path__) {
            if (!isPro) {
                return gulp.src(path_)
                    .pipe(ejs({
                        root: '/admin',
                        domain: 'localhost'
                    }).on('error', function(err){
                        gutil.log(err);
                        this.emit('end');
                    }))
                    .pipe(gulpif('*.js', uglify().on('error', function(err){
                        gutil.log(err);
                        this.emit('end');
                    })))
                    .pipe(useref({}, lazypipe().pipe(sourcemaps.init, {loadMaps: true})))
                    // .pipe(rev())
                    .pipe(sourcemaps.write('maps'))
                    .pipe(gulp.dest(path__))
            } else {
                return gulp.src(path_)
                    .pipe(ejs({
                        root: '/admin',
                        domain: '123.57.39.2'
                    }).on('error', function(err){
                        gutil.log(err);
                        this.emit('end');
                    }))
                    .pipe(useref({}))
                    // .pipe(gulpif('*.js', uglify()))
                    .pipe(gulpif('*.js', uglify().on('error', function(err){
                        gutil.log(err);
                        this.emit('end');
                    })))
                    .pipe(gulpif('*.css', minifyCss()))
                    .pipe(gulp.dest(path__))
            }


        }
    }
}

gulp.task('include-without-img-libs', function () {
    readOneLevelFile(htmlDir);
    /**
     * 图片处理
     */
    // gulp.src('src.test/imgs/**/*.*')    //原图片的位置
    //     .pipe(imagemin())                   //执行图片压缩
    //     .pipe(gulp.dest('build/imgs'));
    /**
     * 第三方库脚本库
     */
    // gulp.src('src.test/libs/**/*.*')    //原脚本的位置
    //     .pipe(gulp.dest('build/libs'));
    /**
     * 系统脚本
     */
    gulp.src('src.test/script/**/*.*')    //原脚本的位置
        .pipe(gulp.dest('build/script'));
    /**
     * 样式文件
     */
    gulp.src('src.test/styles/*.*')    //原样式的位置
        .pipe(gulp.dest('build/styles'));
    /**
     * 打包公用js
     */
    return gulp.src('src.test/js/common.js')
        .pipe(gulp.dest('build/js/common.js'));

});
gulp.task('include', function () {
    readOneLevelFile(htmlDir);
    /**
     * 图片处理
     */
    gulp.src('src.test/imgs/**/*.*')    //原图片的位置
        .pipe(imagemin())                   //执行图片压缩
        .pipe(gulp.dest('build/imgs'));
    /**
     * 第三方库脚本库
     */
    gulp.src('src.test/libs/**/*.*')    //原脚本的位置
        .pipe(gulp.dest('build/libs'));
    /**
     * 系统脚本
     */
    gulp.src('src.test/script/**/*.*')    //原脚本的位置
        .pipe(gulp.dest('build/script'));
    /**
     * 样式文件
     */
    gulp.src('src.test/styles/*.*')    //原样式的位置
        .pipe(gulp.dest('build/styles'));
    /**
     * 打包公用js
     */
    gulp.src('src.test/js/common.js')
        .pipe(gulp.dest('build/js/common.js'));

    return  copyFont();

});
gulp.task('dist:pre-start', function () {
    return del('build/**/*').then(function (paths) {
        console.log('Deleted files and folders:\n', paths.join('\n'));
    })
});

gulp.task('dist:step1', function () {
    readOneLevelFile(htmlDir, true);

    /**
     * 第三方库脚本库
     */
    gulp.src('src.test/libs/**/*.*')    //原脚本的位置
        .pipe(gulp.dest('build/libs'));
    /**
     * 系统脚本
     */
    gulp.src('src.test/script/**/*.*')    //原脚本的位置
        .pipe(gulp.dest('build/script'));
    /**
     * 样式文件
     */
    gulp.src('src.test/styles/*.*')    //原样式的位置
        .pipe(gulp.dest('build/styles'));
    /**
     * 打包公用js
     */
    gulp.src('src.test/js/common.js')
        .pipe(gulp.dest('build/js/common.js'));
    /**
     * 图片处理
     */
    return gulp.src('src.test/imgs/**/*.*')    //原图片的位置
        .pipe(imagemin())                   //执行图片压缩
        .pipe(gulp.dest('build/imgs'));

});
gulp.task('dist:step2:css', function () {
    return gulp.src(['build/**/*.css', '!build/libs/**/*.css'])
        .pipe(rev())
        .pipe(gulp.dest('build'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('build/rev/css'))
});
gulp.task('dist:step3:js', function () {
    return gulp.src(['build/**/*.js', 'build/**/*.js', '!build/libs/**/*.js'])
        .pipe(rev())
        .pipe(gulp.dest('build'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('build/rev/js'))
});
gulp.task('dist:step4:rev', function () {
    return gulp.src(['build/rev/**/*.json', 'build/**/*.html'])
        .pipe(revCollector({
            replaceReved: true,
        }))
        .pipe(gulp.dest('build'));
});

gulp.task('dist:step5', function () {
    return gulp.src(['build/**/*.html', '!build/libs/**/*.html', '!build/common/*.html', '!build/script/**/*.html', '!build/scripts/**/*.html'])
        .pipe(htmlmin({
            removeComments: true,
            collapseWhitespace: true,
            // ignoreStartTag:/\<\$/,
            // ignoreEndTag:/\$\>/,
            ignoreCustomFragments: [/\<\$[\s\S]*?\$\>/, /\<\$=[\s\S]*?\$\>/, /\<\%\-[\s\S]*?\%\>/],
            ignoreCustomComments: [/^!/],
            minifyJS: true,
            minifyCSS: true
        }))
        .pipe(gulp.dest('build'));

});
gulp.task('sequence-dist', gulpSequence('dist:pre-start', 'dist:step1', ['dist:step2:css', 'dist:step3:js'], 'dist:step4:rev', 'dist:step5','copy-font'));
// gulp.task('sequence-dist', gulpSequence('dist:step1','dist:step2:css', 'dist:step3:js', 'dist:step4:rev',  'dist:step5'));
gulp.task('sequence-dev', gulpSequence('dev:step1', ['dist:step2:css', 'dist:step3:js'], 'dist:step4:rev'));

/**
 * 最小化
 */
gulp.task('minhtml', function () {
    return gulp.src('build/*.*')
        .pipe(htmlmin({
            collapseWhitespace: true,
            ignoreStartTag: /\<\$/,
            ignoreEndTag: /\$\>/,
            ignoreCustomComments: [/^!/],
//            customAttrSurround:[[/\<\$/,/\$\>/]],
            minifyJS: true, minifyCSS: true
        }))
        .pipe(gulp.dest('build'));
});

/**
 * @author byte_su@163.com
 * @date 2017-05-04 16:00
 * @desc 读取同层级文件处理，判断目录递归处理
 * @param dir_
 * @param isPro true 表示生产环境构建
 */
function readOneLevelFile(dir_, isPro) {
    fs.readdir(dir_, function (err, files) {
        if (err) {
            console.log(err);
        } else {
            files.forEach(function (f) { //
                var path_ = (dir_ + f);
                var fd = fs.openSync(path_, 'r');
                var obj_file = fs.fstatSync(fd);
                if (obj_file.isFile() && path.extname(path_).indexOf('.htm') > -1) {
                    if (path_.indexOf('.html') > -1 && path_.indexOf('common') == -1 && path_.indexOf('common') == -1) {
                        // var sources = gulp.src(['./build/common/*.js', './build/common/*.css'], {read: false});
                        console.log('处理文件路径->' + path_);
                        // console.log('[处理结果--]->' + dir_.replace('src.test', 'build').replace('html/', ''))
                        singleFileTask(path_, isPro);
                        // gulp.src(path_)
                        // // .pipe(inject(sources))
                        //
                        //     .pipe(ejs({
                        //         root: '/admin'
                        //     }).on('error', gutil.log))
                        //     .pipe(useref({}))
                        //     // .pipe(gulpif('*.js', uglify()))
                        //     // .pipe(gulpif('*.css', minifyCss()))
                        //     // .pipe(rev())
                        //     .pipe(gulp.dest(dir_.replace('src.test', 'build').replace('html/', '')))
                    } else {
                        console.log('非处理文件->' + path_);
                    }
                } else if (obj_file.isDirectory()) {
                    readOneLevelFile(path_ + '/', isPro);
                } else {
                    console.log('非处理文件->' + path_);
                }
            });
        }
    });
}